package at.fhj.itm11.forum.beans;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
import javax.inject.Inject;
import javax.inject.Named;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import at.fhj.itm11.forum.service.PostService;
import at.fhj.itm11.forum.service.dtos.PostDTO;

@ManagedBean
@RequestScoped
public class MediaBean {

	@Inject
	@Named("postServiceImpl")
	private PostService postService;

	private FacesContext facesContext;
	private ExternalContext externalContext;

	@PostConstruct
	public void init() {
		facesContext = FacesContext.getCurrentInstance();
		externalContext = facesContext.getExternalContext();
	}

	public StreamedContent getImage() throws IOException {
		if (facesContext.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
			return new DefaultStreamedContent();
		} else {
			String id = externalContext.getRequestParameterMap().get("id");
			PostDTO post = postService.findById(Long.parseLong(id));
			if (post.getImage() != null) {
				return new DefaultStreamedContent(new ByteArrayInputStream(
						post.getImage()));

			} else {
				return new DefaultStreamedContent();
			}
		}
	}

	public StreamedContent getVideo() throws IOException {
		if (facesContext.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
			return new DefaultStreamedContent();
		} else {
			String id = externalContext.getRequestParameterMap().get("id");
			PostDTO post = postService.findById(Long.parseLong(id));
			if (post.getVideo() != null) {
				return new DefaultStreamedContent(new ByteArrayInputStream(
						post.getVideo()));

			} else {
				return new DefaultStreamedContent();
			}
		}
	}

	public void setPostService(PostService postService) {
		this.postService = postService;
	}

	public void setFacesContext(FacesContext facesContext) {
		this.facesContext = facesContext;
	}

	public void setExternalContext(ExternalContext externalContext) {
		this.externalContext = externalContext;
	}

}
